<template>
  <div class="main-container">
    <el-card class="box-card !border-none" shadow="never">
      <el-page-header
        :content="formData.goods_id ? t('updateText') : t('addText')"
        :icon="ArrowLeft"
        @back="$router.back()"
      />
    </el-card>
    <el-card class="box-card mt-[15px] !border-none" shadow="never">
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane :label="t('baseInfoTab')" name="1">
          <el-form
            :model="formData"
            label-width="120px"
            ref="basicFormRef"
            :rules="formRules"
            class="page-form"
          >
            <el-form-item :label="t('liveType')">
              <el-radio-group
                v-model="formData.live_play_protocol"
                >
                <el-radio
                  value="m3u8"
                  :label="t('slowLivestreaming')"></el-radio>
                <el-radio
                  value="webrtc"
                  :label="t('livestreamingQuickly')"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="t('activityTitle')" prop="title">
              <el-input
                v-model.trim="formData.title"
                clearable
                :placeholder="t('activityTitlePlaceholder')"
                class="max-w-[400px]"
                maxlength="60"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="t('activityCategory')" prop="cate_id">
              <el-select
                v-model.trim="formData.cate_id"
                clearable
                :placeholder="t('activityCategoryPlaceholder')"
                class="min-w-[400px]">
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item :label="t('activityLiveTime')" prop="play_date">
              <el-date-picker
                type="datetimerange"
                v-model.trim="formData.play_date"
                value-format="YYYY-MM-DD HH:mm:ss"
                clearable
                :start-placeholder="t('activityLiveTimeStartPlaceholder')"
                :end-placeholder="t('activityLiveTimeEndPlaceholder')"
                class="max-w-[400px]"
              />
            </el-form-item>
            <!-- <el-form-item :label="t('activityPlaybackTime')">
              <el-date-picker
                type="datetimerange"
                v-model.trim="formData.huifang_date"
                value-format="YYYY-MM-DD HH:mm:ss"
                clearable
                :start-placeholder="t('activityPlaybackTimeStartPlaceholder')"
                :end-placeholder="t('activityPlaybackTimeEndPlaceholder')"
                class="max-w-[400px]"
              />
            </el-form-item> -->
            <el-form-item :label="t('shareTitle')">
              <el-input
                v-model.trim="formData.share_title"
                clearable
                :placeholder="t('shareTitlePlaceholder')"
                class="max-w-[400px]"
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="t('shareDesc')">
              <el-input
                type="textarea"
                v-model.trim="formData.share_desc"
                clearable
                :placeholder="t('shareDescPlaceholder')"
                class="max-w-[400px]"
              />
            </el-form-item>
            <el-form-item :label="t('shareImage')" prop="goods_image">
              <div>
                <upload-image v-model="formData.share_image" :limit="1" />
                <div class="text-[#999] text-[12px]">
                  {{ t("shareImageTips") }}
                </div>
              </div>
            </el-form-item>
            <el-form-item :label="t('backgroundImage')" prop="goods_image">
              <div>
                <upload-image v-model="formData.back_image" :limit="1" />
                <div class="text-[#999] text-[12px]">
                  {{ t("backgroundImageTips") }}
                </div>
              </div>
            </el-form-item>
            <el-form-item :label="t('remindImage')" prop="tips_src">
              <div>
                <upload-image v-model="formData.tips_src" :limit="1" />
                <div class="text-[#999] text-[12px]">
                  {{ t("remindImageTips") }}
                </div>
              </div>
            </el-form-item>
            <el-form-item :label="t('status')" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio-button :label="$convert(1, formData.status)">{{ t("statusOn") }}</el-radio-button>
                <el-radio-button :label="$convert(0, formData.status)">{{
                  t("statusOff")
                }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="t('autoOnlineOrOffline')">
              <span class="mr-[10px]">{{ t("online") }}</span>
              <el-date-picker
                type="datetime"
                v-model.trim="formData.online_time"
                clearable
                :placeholder="t('onlinePlaceholder')"
                class="w-[200px]"
              />
              <span class="mr-[10px] ml-[15px]">{{ t("offline") }}</span>
              <el-date-picker
                type="datetime"
                v-model.trim="formData.offline_time"
                clearable
                :placeholder="t('offlinePlaceholder')"
                class="w-[200px]"
              />
            </el-form-item>
            <el-form-item :label="t('liveStyle')">
              <el-radio-group v-model="formData.style">
                <el-radio-button :label="$convert(1, formData.style)">{{
                  t("liveStyleHorizontally")
                }}</el-radio-button>
                <el-radio-button :label="$convert(0, formData.style)">{{
                  t("liveStyleVertical")
                }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="t('answerRewardTab')" name="2">
          <el-form
            :model="formData"
            label-width="120px"
            ref="priceStockFormRef"
            :rules="formRules"
            class="page-form"
          >
            <el-form-item :label="t('answerSetting')" prop="spec_type">
              <span class="mr-[10px]">{{
                t("answerSettingText").split(",")[0]
              }}</span>
              <el-input
                v-model.number="formData.dati_time"
                clearable
                :placeholder="t('answerSettingPlaceholder')"
                class="max-w-[100px]"
              />
              <span class="ml-[10px]">{{
                t("answerSettingText").split(",")[1]
              }}</span>
            </el-form-item>
            <el-form-item :label="t('answerTimes')" prop="answerTimes">
              <div>
                <div>
                  <el-input
                    v-model.number="formData.daticount"
                    clearable
                    :placeholder="t('answerTimesPlaceholder').split(',')[0]"
                    class="max-w-[100px]"
                  />
                  <span class="ml-[10px]">{{
                    t("answerTimesText").split(",")[0]
                  }}</span>

                  <span class="mr-[10px] ml-[15px]">{{
                    t("answerTimesText").split(",")[1]
                  }}</span>
                  <el-input
                    v-model.number="formData.zhouqi"
                    clearable
                    :placeholder="t('answerTimesPlaceholder').split(',')[1]"
                    class="max-w-[100px]"
                  />
                  <span class="ml-[10px]">{{
                    t("answerTimesText").split(",")[2]
                  }}</span>

                  <span class="mr-[10px] ml-[15px]">{{
                    t("answerTimesText").split(",")[3]
                  }}</span>
                  <el-input
                    v-model.number="formData.tishu"
                    clearable
                    :placeholder="t('answerTimesPlaceholder').split(',')[2]"
                    class="max-w-[100px]"
                  />
                  <span class="ml-[10px]">{{
                    t("answerTimesText").split(",")[4]
                  }}</span>

                  <span class="mr-[10px] ml-[15px]">{{
                    t("answerTimesText").split(",")[5]
                  }}</span>
                  <el-input
                    v-model.number="formData.zhengqueshu"
                    clearable
                    :placeholder="t('answerTimesPlaceholder').split(',')[3]"
                    class="max-w-[100px]"
                  />
                  <span class="ml-[10px]">{{
                    t("answerTimesText").split(",")[6]
                  }}</span>
                </div>
                <div class="text-[#999] text-[12px]">
                  {{ t("answerTimesTips") }}
                </div>
              </div>
            </el-form-item>
            <el-form-item :label="t('redMode')" prop="pay_model">
              <div>
                <el-radio-group v-model="formData.pay_model">
                  <el-radio-button
                      :value="$convert(1, formData.pay_model)"
                      :label="t('redModeText').split(',')[0]"></el-radio-button>
                    <el-radio-button
                      :value="$convert(2, formData.pay_model)"
                      :label="t('redModeText').split(',')[1]"></el-radio-button>
                    <el-radio-button
                      :value="$convert(3, formData.pay_model)"
                      :label="t('redModeText').split(',')[2]"></el-radio-button>
                </el-radio-group>
                <div class="text-[#999] text-[12px]">
                  {{ t("redModeTips") }}
                </div>
              </div>
            </el-form-item>
            <el-form-item :label="t('redSetting')" prop="spec_type" v-if="formData.pay_model !== 2">
              <div>
                <div>
                  <span class="mr-[10px]">{{
                    t("redSettingText").split(",")[0]
                  }}</span>
                  <el-input
                    v-model.number="formData.hongbaocount"
                    clearable
                    :placeholder="t('redSettingPlaceholder').split(',')[0]"
                    class="max-w-[100px]"
                  />
                  <span class="ml-[10px] mr-[15px]">{{
                    t("redSettingText").split(",")[1]
                  }}</span>

                  <span class="mr-[10px]">{{
                    t("redSettingText").split(",")[2]
                  }}</span>
                  <el-input
                    v-model.trim="formData.hongbao_min"
                    clearable
                    :placeholder="t('redSettingPlaceholder').split(',')[1]"
                    class="max-w-[100px]"
                    @input="hongbaocountChange"
                  />
                  <span class="ml-[10px] mr-[15px]">{{
                    t("redSettingText").split(",")[3]
                  }}</span>

                  <span class="mr-[10px]">{{
                    t("redSettingText").split(",")[4]
                  }}</span>
                  <el-input
                    v-model.trim="formData.jifen_min"
                    clearable
                    :placeholder="t('redSettingPlaceholder').split(',')[2]"
                    class="max-w-[100px]"
                    @input="jifenminChange"
                  />
                  <span class="ml-[10px] mr-[15px]">{{
                    t("redSettingText").split(",")[5]
                  }}</span>
                </div>
                <div class="text-[#999] text-[12px]">
                  {{ t("redSettingTips") }}
                </div>
              </div>
            </el-form-item>
            <el-form-item :label="t('luckySetting')" prop="spec_type">
              <span class="mr-[10px]">{{
                t("luckySettingText").split(",")[0]
              }}</span>
              <el-input
                v-model.number="formData.fudai_shijian"
                clearable
                :placeholder="t('luckySettingPlaceholder').split(',')[0]"
                class="max-w-[100px]"
              />
              <span class="ml-[10px] mr-[15px]">{{
                t("luckySettingText").split(",")[1]
              }}</span>

              <span class="mr-[10px]">{{
                t("luckySettingText").split(",")[2]
              }}</span>
              <el-input
                v-model.number="formData.fudai_renshu"
                clearable
                :placeholder="t('luckySettingPlaceholder').split(',')[1]"
                class="max-w-[100px]"
              />
              <span class="ml-[10px] mr-[15px]">{{
                t("luckySettingText").split(",")[3]
              }}</span>

              <span class="mr-[10px]">{{
                t("luckySettingText").split(",")[4]
              }}</span>
              <el-input
                v-model.number="formData.fudai_meiren"
                clearable
                :placeholder="t('luckySettingPlaceholder').split(',')[2]"
                class="max-w-[100px]"
              />
              <span class="ml-[10px] mr-[15px]">{{
                t("luckySettingText").split(",")[5]
              }}</span>
            </el-form-item>
            <el-form-item :label="t('luckyAwardName')">
              <el-input
                v-model.trim="formData.fudai_name"
                clearable
                :placeholder="t('luckyAwardNamePlaceholder')"
                class="max-w-[400px]"
              />
            </el-form-item>
            <el-form-item :label="t('luckyComment')">
              <el-input
                type="textarea"
                v-model.trim="formData.fudai_pinglun"
                clearable
                :placeholder="t('luckyCommentPlaceholder')"
                class="max-w-[400px]"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="t('rewardTab')" name="3">
          <el-form
            :model="formData"
            label-width="120px"
            ref="deliveryFormRef"
            :rules="formRules"
            class="page-form"
          >
            <el-form-item :label="t('encryptViewing')">
              <div>
                <el-input
                  v-model.trim="formData.play_pwd"
                  clearable
                  :placeholder="t('encryptViewingPlaceholder')"
                  class="min-w-[400px]"
                />
                <div class="text-[#999] text-[12px]">
                  {{ t("encryptViewingTips") }}
                </div>
              </div>
            </el-form-item>
            <!-- <el-form-item :label="t('levelLimit')">
              <div>
                <el-input
                  v-model.trim="formData.goods_name"
                  clearable
                  :placeholder="t('levelLimitPlaceholder')"
                  class="min-w-[400px]"
                />
                <div class="text-[#999] text-[12px]">
                  {{ t("levelLimitTips") }}
                </div>
              </div>
            </el-form-item>
            <el-form-item :label="t('tagLimit')">
              <div>
                <el-input
                  v-model.trim="formData.goods_name"
                  clearable
                  :placeholder="t('tagLimitPlaceholder')"
                  class="min-w-[400px]"
                />
                <div class="text-[#999] text-[12px]">
                  {{ t("tagLimitTips") }}
                </div>
              </div>
            </el-form-item> -->
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="t('autoLabelTab')" name="4">
          <el-form
            :model="formData"
            label-width="120px"
            ref="goodsArgumentsFormRef"
            :rules="formRules"
            class="page-form"
          >
            <el-form-item :label="t('autoLabel')">
              <div>
                <el-radio-group v-model="formData.auto_tag_status">
                  <el-radio-button :label="$convert(0, formData.auto_tag_status)">{{
                    t("autoLabelText").split(",")[0]
                  }}</el-radio-button>
                  <el-radio-button :label="$convert(1, formData.auto_tag_status)">{{
                    t("autoLabelText").split(",")[1]
                  }}</el-radio-button>
                </el-radio-group>
                <el-table class="mt-[10px]">
                  <el-table-column
                    prop="name"
                    :label="t('autoLabelColumn').split(',')[0]"
                    width="200"
                  />
                  <el-table-column
                    prop="value"
                    :label="t('autoLabelColumn').split(',')[1]"
                    width="300"
                  />
                  <el-table-column
                    prop="value"
                    :label="t('autoLabelColumn').split(',')[2]"
                    width="100"
                  >
                    <template #default="scope">
                      <el-button type="primary" size="small">{{
                        t("autoLabelSet")
                      }}</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="t('otherInfoTab')" name="5">
          <el-form
            :model="formData"
            label-width="120px"
            ref="detailFormRef"
            :rules="formRules"
            class="page-form"
          >
            <el-form-item :label="t('virtualViewers')">
              <div>
                <el-input
                  v-model.trim="formData.playnum"
                  clearable
                  :placeholder="t('virtualViewersPlaceholder')"
                  class="min-w-[400px]"
                />
                <div class="text-[#999] text-[12px]">
                  {{ t("virtualViewersTips") }}
                </div>
              </div>
            </el-form-item>
            <el-form-item :label="t('answerSwitch')">
              <el-radio-group v-model="formData.is_open_answer">
                <el-radio-button :label="1">{{
                  t("answerSwitchText").split(",")[0]
                }}</el-radio-button>
                <el-radio-button :label="0">{{
                  t("answerSwitchText").split(",")[1]
                }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="t('commentSwitch')">
              <el-radio-group v-model="formData.chat_open">
                <el-radio-button :label="1">{{
                  t("commentSwitchText").split(",")[0]
                }}</el-radio-button>
                <el-radio-button :label="0">{{
                  t("commentSwitchText").split(",")[1]
                }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="t('contentSwitch')">
              <el-radio-group v-model="formData.is_open_desc">
                <el-radio-button :label="1">{{
                  t("contentSwitchText").split(",")[0]
                }}</el-radio-button>
                <el-radio-button :label="0">{{
                  t("contentSwitchText").split(",")[1]
                }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="t('content')" prop="goods_desc">
              <editor
                v-model="formData.detail"
                :height="600"
                class="editor-width"
                @handleBlur="handleBlur"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <div class="fixed-footer-wrap">
      <div class="fixed-footer">
        <el-button type="primary" @click="save()">{{ t("save") }}</el-button>
        <el-button @click="back()">{{ t("back") }}</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ArrowLeft } from "@element-plus/icons-vue";
import { t } from "@/lang";
import { ref, onMounted, watch, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  addActivityApi,
  editActivityApi,
  getActivityInfoApi,
  getCategoryAllApi,
} from "@/addon/htscrm/api"
import { cloneDeep, debounce } from "lodash-es";
import { FormInstance } from "element-plus";

const instance = getCurrentInstance() as any
const { $convert } = instance?.appContext.config.globalProperties

const route = useRoute()
// 表单验证
const validateAnswerTimes = (rule: any, value: any, callback: any) => {
  if (!formData.value.daticount || formData.value.daticount < 1) {
    callback(new Error("请输入正确的答题次数"));
    return;
  }
  if (!formData.value.zhouqi || formData.value.daticount < 1) {
    callback(new Error("请输入正确的答题周期"));
    return;
  }
  if (!formData.value.tishu || formData.value.daticount < 1) {
    callback(new Error("请输入正确的每次抽的题数"));
    return;
  }
  if (!formData.value.zhengqueshu || formData.value.daticount < 1) {
    callback(new Error("请输入答题正确获得奖励的题数"));
    return;
  }
  callback();
};
const validateActivityPlaybackTime = (rule: any, value: any, callback: any) => {
  if (!formData.value.huifang_date) {
    callback(new Error("请输入回放时间"));
    return;
  }
  callback();
};
const validateActivityLivebackTime = (rule: any, value: any, callback: any) => {
  if (!formData.value.play_date) {
    callback(new Error("请输入直播时间"));
    return;
  }
  callback();
};

const formRules = ref({
  title: [{ required: true, message: t("activityTitleTip"), trigger: "blur" }],
  cate_id: [{ required: true, message: t("activityCateTip"), trigger: "blur" }],
  video_url: [{ required: true, message: "请上传视频", trigger: "blur" }],
  video_time: [{ required: true, message: "请输入视频时长", trigger: "blur" }],
  status: [{ required: true, message: t("statusTip"), trigger: "blur" }],
  pay_model: [{ required: true, message: t("payModelTip"), trigger: "blur" }],
  answerTimes: [
    { required: true, validator: validateAnswerTimes, trigger: "blur" },
  ],
  activityPlaybackTime: [
    {
      required: true,
      validator: validateActivityPlaybackTime,
      trigger: "blur",
    },
  ],
  play_date: [
    {
      required: true,
      validator: validateActivityLivebackTime,
      trigger: "blur",
    },
  ]
});

const hongbaocountChange = (value: string) => {
  
  const regex = /^\d*\.?\d*$/;
  if (!regex.test(value)) {
    // 如果不符合正则表达式，则不更新输入值
    formData.value.hongbao_min = '';
  } else {
    // 否则，更新输入值
    formData.value.hongbao_min = value;
  }
}

const jifenminChange = (value: string) => {
  const regex = /^\d*\.?\d*$/;
  if (!regex.test(value)) {
    // 如果不符合正则表达式，则不更新输入值
    formData.value.jifen_min = '';
  } else {
    // 否则，更新输入值
    formData.value.jifen_min = value;
  }
}

// 当前tab
const activeName = ref("1");

// 表单数据
const formData = ref<any>({
  live_play_protocol: "m3u8",
  pay_model: 1,
  is_open_answer: 1,
  chat_open: 1,
  is_open_desc: 1,
  status: 1,
  style: 1,
  hongbaocount: null,
  auto_tag_status: 0
});

/**
 * tab切换
 */
function handleTabClick() {}

/**
 * 返回
 */
function back() {
  window.history.back();
}

const categoryList = ref<any[]>([]);
async function getCategoryAll() {
  const res = await getCategoryAllApi();
  categoryList.value = res.data;
}

function validate(name: string, formRef?: FormInstance) {
  return new Promise((resolve, reject) => {
    formRef?.validate((valid, errors) => {
      if (valid) {
        resolve(true);
      } else {
        activeName.value = name;
        reject(errors);
      }
    });
  });
}

const basicFormRef = ref<FormInstance>();
const priceStockFormRef = ref<FormInstance>();
const deliveryFormRef = ref<FormInstance>();
const goodsArgumentsFormRef = ref<FormInstance>();
const detailFormRef = ref<FormInstance>();
const isInit = ref(true);
const isChanged = ref(false);

/**
 * 保存
 */
const save = debounce(async (isBack: boolean = true) => {
  await validate("1", basicFormRef.value);
  await validate("2", priceStockFormRef.value);
  await validate("3", deliveryFormRef.value);
  await validate("4", goodsArgumentsFormRef.value);
  await validate("5", detailFormRef.value);
  if (isChanged.value === false) {
    back();
    return;
  }
  const params: any = cloneDeep(formData.value);
  params.play_date = params.play_date ? params.play_date.join(" 到 ") : "";
  params.huifang_date = params.huifang_date
    ? params.huifang_date.join(" 到 ")
    : "";
  // params.daoke_tag_ids = params.auto_tag_list[0].tags
  // params.wanbo_tag_ids = params.auto_tag_list[1].tags
  params.offline_time = params.offline_time
    ? parseInt(String(params.offline_time / 1000))
    : 0;
  params.online_time = params.online_time
    ? parseInt(String(params.online_time / 1000))
    : 0;
  delete params.auto_tag_list;
  params.type = 2
  params.id ? await editActivityApi(params) : await addActivityApi(params);

  isChanged.value = false;
  isBack && back();
});

watch(
  () => formData,
  () => {
    // console.log(formData);
    console.log("内容变了");
    if (!isInit.value) {
      isChanged.value = true;
    }
    isInit.value = false;
  },
  { deep: true }
);

async function getDetail() {
  if (!route.query.id) return;
  const res = await getActivityInfoApi(Number(route.query.id));
  // 处理时间段数据
  res.data.play_date = res.data.play_date
    ? (res.data.play_date as any).split(" 到 ")
    : [];
  res.data.huifang_date = res.data.huifang_date
    ? (res.data.huifang_date as any).split(" 到 ")
    : [];
  res.data.online_time = res.data.online_time
    ? new Date(res.data.online_time).getTime()
    : null;
  res.data.offline_time = res.data.offline_time
    ? new Date(res.data.offline_time).getTime()
    : null;
  // 自动标签
  res.data.auto_tag_list = res.data.auto_tag_list ?? [
    {
      type: 1,
      name: "到课",
      tags: [],
    },
    {
      type: 2,
      name: "完播",
      tags: [],
    },
  ];
  formData.value = res.data;
}

onMounted(() => {
  getDetail();
  getCategoryAll();
});
</script>

<style lang="scss" scoped></style>
